<template>
    <div class="indices-forecast">
      <h1>生活指南</h1>
      <div v-if="weatherWarning" class="weather-warning-message">
        <p>{{ weatherWarning }}</p>
      </div>
      <div v-if="!location.lat || !location.lon" class="error-message">
        <p>正在获取位置信息...</p>
      </div>
      
      <div class="indices-container">
        <div 
          v-for="type in indicesTypes" 
          :key="type.value"
          class="index-card"
          :class="{ active: selectedTypes.includes(type.value) }"
          @click="toggleType(type.value)"
        >
          <span class="index-name">{{ type.label }}</span>
        </div>
      </div>
  
      <div v-if="selectedTypes.length === 0" class="warning-message">
        请至少选择一个指数类型
      </div>
  
      <div v-if="indexData" class="indices-results">
        <div class="indices-grid">
          <div v-for="(item, index) in indexData.daily" 
            :key="index" 
            class="index-item"
          >
            <div class="index-header">
              <h3>{{ item.name }}</h3>
              <span class="category" :class="getCategoryClass(item.category)">
                {{ item.category }}
              </span>
            </div>
            <p class="description">{{ item.text }}</p>
          </div>
        </div>
      </div>
  
      <div v-if="error" class="error-message">
        <p>错误信息：{{ error }}</p>
      </div>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  import { mapState } from 'vuex';
  import { KEY, API_INDICES } from '@/common/constrant';

  
  export default {
    name: 'IndicesForecast',
    data() {
      return {
        weatherWarning: null,  //用来存储天气预警信息
        selectedTypes: ['1', '3', '6', '7', '13','14'], // 修改默认选中的指数
        indexData: null,
        error: null,
        indicesTypes: [
          { value: '1', label: '运动指数' },
          { value: '3', label: '穿衣指数' },
          { value: '6', label: '紫外线指数' },
          { value: '7', label: '空气污染' },
          { value: '13', label: '交通指数' },
          { value: '14', label: '钓鱼指数' }
        ]
      };
    },
    computed: {
      ...mapState({
        location: state => state.location,
      })
    },
    created() {
      this.fetchWeatherWarning();
    },
    methods: {
      toggleType(value) {
        const index = this.selectedTypes.indexOf(value);
        if (index === -1) {
          this.selectedTypes.push(value);
          this.fetchIndices();
        } else {
          if (this.selectedTypes.length > 1) {
            this.selectedTypes.splice(index, 1);
            this.fetchIndices();
          }
        }
      },
      getCategoryClass(category) {
        // 根据不同的等级返回不同的样式类名
        const levelMap = {
          '较适宜': 'level-good',
          '适宜': 'level-excellent',
          '较不宜': 'level-bad',
          '不宜': 'level-terrible'
        };
        return levelMap[category] || 'level-normal';
      },
      async fetchIndices() {
        try {
          if (!this.location.id) {
            this.error = '位置信息未获取，请稍后再试';
            return;
          }
  
          if (this.selectedTypes.length === 0) {
            this.indexData = null;
            return;
          }
  
          const url = API_INDICES;
          const params = {
            location: this.location.id,
            type: this.selectedTypes.join(','),
            key: KEY,
            lang: 'zh'
          };
  
          const response = await axios.get(url, { params });
  
          if (response.data.code === '200') {
            this.indexData = response.data;
            this.error = null;
          } else {
            throw new Error(`API error code: ${response.data.code}`);
          }
        } catch (error) {
          console.error('API error:', error);
          this.error = error.message;
        }
      },
      async fetchWeatherWarning() {
         try {
          if (!this.location.id) {
            this.weatherWarning = null;
            return;
          }
          const warningUrl = "https://devapi.qweather.com/v7/warning/now"; 
          const warningParams = {
            location: this.location.id,
            key:KEY,
          };
          const response = await axios.get(warningUrl, { params: warningParams });
          if (response.data.code === '200') {
            this.weatherWarning = response.data.warningInfo; // 根据实际接口返回的数据结构来正确赋值
          } else {
            throw new Error(`Weather warning API error code: ${response.data.code}`);
          }
        } catch (error) {
          console.error('Weather warning API error:', error);
          this.weatherWarning = null;
        }
      }
    },
    watch: {
      'location.id': {
        handler(newVal) {
          if (newVal) {
            this.fetchIndices();
          }
        },
        immediate: true
      }
    }
  };
  </script>
  
  <style scoped>
  .indices-forecast {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
  }
  
  .indices-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 10px;
    margin: 20px 0;
  }
  
  .index-card {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 8px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
    background-color: #f5f5f5;
  }
  
  .index-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .index-card.active {
    background-color: #4CAF50;
    color: white;
    border-color: #4CAF50;
  }
  
  .indices-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 20px;
    margin-top: 20px;
  }
  
  .index-item {
    border: 1px solid #eee;
    border-radius: 12px;
    padding: 20px;
    background-color: white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    transition: transform 0.2s ease;
  }
  
  .index-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  }
  
  .index-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }
  
  .index-header h3 {
    margin: 0;
    color: #333;
  }
  
  .category {
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 0.9em;
    font-weight: bold;
  }
  
  .level-excellent { background-color: #4CAF50; color: white; }
  .level-good { background-color: #8BC34A; color: white; }
  .level-normal { background-color: #FFC107; color: black; }
  .level-bad { background-color: #FF9800; color: white; }
  .level-terrible { background-color: #F44336; color: white; }
  
  .description {
    color: #666;
    line-height: 1.5;
    margin: 0;
  }
  
  .error-message {
    color: #f44336;
    padding: 10px;
    border: 1px solid #f44336;
    border-radius: 8px;
    margin-top: 10px;
    text-align: center;
  }
  
  .warning-message {
    color: #ff9800;
    padding: 10px;
    border: 1px solid #ff9800;
    border-radius: 8px;
    margin: 10px 0;
    text-align: center;
    background-color: #fff3e0;
  }

  .weather-warning-message {
  color: #f44336;
  padding: 10px;
  border: 1px solid #f44336;
  border-radius: 8px;
  margin-top: 10px;
  text-align: center;
}
  </style>